<template>
  <a-form
    ref="formRef"
    v-model:model="itemModel"
    :label-col="labelCol"
    :wrapper-col="wrapperCol"
    @finish="onFinish"
    @finishFailed="onFinishFailed"
  >
    <r-h-item v-for="(item,index) in formItem" v-show="itemShow(item)" :key="index" v-model:form="itemModel" :item="item" />
  </a-form>
</template>

<script lang="ts">
import { defineComponent, ref, toRef } from 'vue'
import RHItem from '@/components/RHForm/RHItem/index.vue'
import _ from 'lodash'
export default defineComponent({
  name: 'RHForm',
  components: { RHItem },
  props: {
    /**
     * 隐藏所有表单项的必选标记
     */
    hideRequiredMark: {
      type: Boolean,
      default: false
    },
    /**
     * 标签文本对齐方式
     */
    labelAlign: {
      type: String,
      default: 'left',
      validator: (value:string) => {
        // 这个值必须与下列字符串中的其中一个相匹配
        return ['left', 'right'].includes(value)
      }
    },
    /**
     * 表单项
     */
    formItem: Array,
    /**
     * 表单
     */
    formModel: {
      type: Object,
      default: () => {}
    },
    type: {
      type: String,
      default: 'Create'
    },
    onFinish: Function,
    onFinishFailed: Function
  },
  setup(props) {
    // 表单数据模型
    const formModel = toRef(props, 'formModel')
    const formRef = ref()
    const getFormRef = () => {
      return formRef.value
    }
    const formItem = toRef(props, 'formItem')
    const itemModel = ref<any>({})
    formItem.value?.forEach((x:any) => {
      itemModel.value[x.dataIndex] = null
      if (x.value) {
        itemModel.value[x.dataIndex] = x.value
      }
    })
    itemModel.value = _.assignIn(itemModel.value, formModel.value)
    // 表单项显示
    const type = toRef(props, 'type')
    const itemShow = (item:any) => {
      if (!item.showType) {
        return false
      }
      return _.findIndex(item.showType, type)
    }
    // 表单验证规则
    const rules:any = ref({})

    return {
      itemModel,
      rules,
      formRef,
      getFormRef,
      itemShow,
      labelCol: { span: 3 },
      wrapperCol: { span: 14 }
    }
  },
  data() {
    return {
    }
  }
})
</script>

<style scoped></style>
